package com.tool4j.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Base64;

@Slf4j
public class Base64Util {

    /**
     * 图片转base64
     *
     * @param file
     * @return
     */
    public static String fileToBase64(MultipartFile file) {
        try {
            String base64 = Base64.getEncoder().encodeToString(file.getBytes());
            String imgType = file.getContentType();
            return String.format("data:%s;base64,%s", imgType, base64);
        } catch (Exception e) {
            log.error("失败");
        }
        return "解析失败";
    }

    /**
     * 图片转Base64字符串
     *
     * @param inputStream
     * @return
     */
    public static String inputStreamToBase64(InputStream inputStream) {
        try {
            //通过字节数组流获取字节数组
            byte[] bytes = inputStream.readAllBytes();
            //获取JDK8里的编码器Base64.Encoder转为base64字符
            return "data:image/png;base64," + Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
